package com.cennavi.minemapdemo.activity.exlayer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.util.Config;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.HistogramLayer;
import com.minedata.minemap.overlay.HistogramLayerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//柱状图层Demo
public class HistogramActivity extends AppCompatActivity {
    private MapView mapView;
    private static MineMap mineMap;
    private HistogramLayer histogramLayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);

        setContentView(R.layout.activity_main_layer);
        mapView = findViewById(R.id.mapView);
        mapView.setApiBaseUrl(Config.API_BASE_URL);
        mapView.setApiUrl(Config.API_URL);
        mapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(final MineMap mineMap) {
                HistogramActivity.mineMap = mineMap;
                mineMap.setStyleUrl(Config.BASE_URL + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {

                    @Override
                    public void onStyleLoaded(String s) {

                        //默认显示路况
                        mineMap.setTrafficShow(true);
                        //60秒刷新一次
                        mineMap.setTrafficRote(60);
                        addHistogramGraphics();
                    }
                });
                mineMap.setRepaint(true);
                //不显示指南针
                mineMap.getUiSettings().setCompassEnabled(false);
                //不可以旋转地图
                mineMap.getUiSettings().setRotateGesturesEnabled(false);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder()
                                .target(new LatLng(39.897424, 116.356508))//设置相机指向的位置
                                .zoom(13)//设置相机缩放等级
                                .tilt(60)//设置相机的俯视角度
                                .bearing(0)//摄像机指向的方向,从北部顺时针方向设置
                                .build());
                //设置是否显示地图调试信息，默认是不显示
                mineMap.setDebugActive(false);
            }
        });
    }

    //添加柱状图层
    public void addHistogramGraphics() {
        HistogramLayerOptions options = new HistogramLayerOptions("histogramlayer");
        options.addAll(getHistogramData(loadJsonFromAsset("histogram_data.json", HistogramActivity.this)));
        histogramLayer = mineMap.addLayer(options);
    }

    //获取柱状图数据
    public List<HistogramLayerOptions.HistogramItem> getHistogramData(String data) {
        if (data.isEmpty()) {
            return null;
        }

        List<HistogramLayerOptions.HistogramItem> items = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(data);
            for (int i = 0; i < array.length(); i++) {
                JSONObject json = new JSONObject(array.get(i).toString());
                String latitude = json.get("latitude").toString();
                String longitude = json.get("longitude").toString();
                LatLng latLng = new LatLng(Double.valueOf(latitude), Double.valueOf(longitude));

                if (i < 5) {
                    List<LatLng> latLngs = new ArrayList<>();
                    latLngs.add(new LatLng(latLng.getLatitude(), latLng.getLongitude()));
                    latLngs.add(new LatLng(latLng.getLatitude(), latLng.getLongitude() - 0.001));
                    latLngs.add(new LatLng(latLng.getLatitude() - 0.001, latLng.getLongitude() - 0.001));
                    latLngs.add(new LatLng(latLng.getLatitude() - 0.001, latLng.getLongitude()));
                    HistogramLayerOptions.HistogramItem item = new HistogramLayerOptions.HistogramItem(
                            latLngs);
                    item.color(Color.parseColor("#ff00ff00"));
                    item.baseHeight(300.0f);
                    item.height(400.0f + 10 * i);
                    items.add(item);
                } else {
                    HistogramLayerOptions.Builder builder =
                            new HistogramLayerOptions.Builder(latLng);
                    builder.count(4);
                    builder.radius(80.0f);
                    HistogramLayerOptions.HistogramItem item = builder.build();
                    item.color(Color.parseColor("#00F8FF"));
                    item.baseHeight(300.0f);
                    item.height(400.0f + 10 * i);
                    items.add(item);
                }
            }

            for (int i = 0; i < 10000; i++) {
                double latitude = Math.random() * 1 + 39;
                double longitude = Math.random() * 1 + 116;
                HistogramLayerOptions.Builder builder =
                        new HistogramLayerOptions.Builder(new LatLng(Double.valueOf(latitude),
                                Double.valueOf(longitude)));
                builder.count(4);
                builder.radius(80.0f);
                HistogramLayerOptions.HistogramItem item = builder.build();
                if (i % 2 == 1) {
                    item.color(Color.parseColor("#00F8FF"));
                } else {
                    item.color(Color.parseColor("#ff00ff00"));
                }

                item.baseHeight(300.0f);
                item.height(400.0f);
                items.add(item);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return items;
    }

    //从Asset文件夹中读取json数据
    private static String loadJsonFromAsset(String filename, Context context) {
        try {
            InputStream is = context.getAssets().open(filename);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer, "UTF-8");
        } catch (Exception e) {
        }
        return null;
    }

    @Override
    protected void onStart() {
        if (mapView != null) {
            mapView.onStart();
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        if (mapView != null)
            mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mapView != null)
            mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mapView != null)
            mapView.onStop();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (mapView != null)
            mapView.onDestroy();
        super.onDestroy();
    }

    public void btnTest(View view) {
        mineMap.snapshot(new MineMap.OnSnapshotReadyCallback() {
            @Override
            public void onSnapshotReady(Bitmap snapshot) {
                //图片存放路径
                String sdCardDir = "/storage/emulated/0/Android/data/com.minedata.minemap/files/";

                try {
                    File dirFile = new File(sdCardDir);
                    if (!dirFile.exists()) {
                        dirFile.mkdirs();
                    }
                    //创建日期
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String sdfDate = sdf.format(date);
                    File file = new File(sdCardDir, "snapshot" + "(" + sdfDate + ")" + ".png");
                    FileOutputStream fos = new FileOutputStream(file);
                    snapshot.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
